import { UseOptions } from '../../interface/cmd'
import { readFile } from '../../utils'
import { handlePathSnd } from './handlePathSnd'
import generateFileSnd from './generateFileSnd'
import { openFile, useLog } from '../cmd'
import { generateJsTemplate, generateTsTemplate } from '../template'
import path from 'path'
import { SwaggerDocSnd, SwaggerDocTnd } from '../../interface/swagger'
import handlePathsTnd from './handlePathsTnd'
import generateFileTnd from './generateFileTnd'
export default async function useJsonMode(filePath: string, option: UseOptions) {
  const _files = await readFile(filePath)
  const files: any = JSON.parse(_files)
  const version = files.swagger ? files.swagger.charAt(0) : files.openapi.charAt(0)
  await openFile(option.path)
  if (version === '2') {
    useLog.info('use openApi-2 rules\n')
    await useOpenApi2(files, option)
  } else {
    useLog.info('use openApi-3 rules\n')
    await useOpenApi3(files, option)
  }
}

async function useOpenApi2(files: SwaggerDocSnd, option: UseOptions) {
  const paths = handlePathSnd(files, option)
  const tsDefineDirname = path.join(__dirname, option.path)
  const { writeDefine, writeTs } = generateFileSnd(files, option, paths)
  const writeTemplate = option.js
    ? generateJsTemplate(tsDefineDirname)
    : generateTsTemplate(tsDefineDirname)
  await Promise.all([writeDefine, writeTs, writeTemplate])
}
async function useOpenApi3(files: SwaggerDocTnd, option: UseOptions) {
  const paths = handlePathsTnd(files, option)
  const tsDefineDirname = path.join(__dirname, option.path)
  const { writeDefine, writeTs } = generateFileTnd(files,option,paths)
  const writeTemplate = option.js
    ? generateJsTemplate(tsDefineDirname)
    : generateTsTemplate(tsDefineDirname)
  await Promise.all([writeDefine, writeTs, writeTemplate])
}
